package cn.edu.lingnan.Interceptor;


import cn.edu.lingnan.entity.Users;
import cn.edu.lingnan.mapper.UserMapper;
import cn.edu.lingnan.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WebInterceptor implements HandlerInterceptor {
    //配置一个线程
    private static final ThreadLocal<Users> current = new ThreadLocal<>();

    @Autowired
    private IUserService iUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");//从前端发送的请求头获取信息
        if (token == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回的码是401
            return false;
        }
        System.out.println(token);
        Users userByToken = iUserService.getUserByToken(token);
        if (userByToken==null){
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);//返回的码是403表示登录失效
            return false;
        }
        current.set(userByToken);
        return true;


    }

    public static Users getUsers(){
     return current.get();
    }








    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        current.remove();
    }



}

